import store from '../store'
import schemeUrl from '../model/schemeUrl'
import {getWechatAuth,getUserInfo,loginByCode,wechatShare,miniLogin,guessSportsText,getTecentCheck} from '@/api/api.js'
import {getCookie} from './cookie.js'
// #ifdef H5
const wxModule = require('jweixin-module')
// #endif

//是否千帆 (默认不展示弹窗)
export function isQianfan(show=false) {
	// #ifdef H5 || APP-PLUS
	let ua = window.navigator.userAgent.toLowerCase()
	if (ua.toLowerCase().search('qianfan') !== -1) {
		return true
	} else {
		if(show){
			uni.showToast({
				title: '身份过期或未登录，请先授权',
				icon:'none'
			})
		}
		return false
	}
	// #endif
	return false
}
//设置分享
export function setShare(val='分享',callback) {
	QFH5.setShareInfo('分享', val, '', '', (state, data) => {
		//回调是所有分享操作的回调，无论从右上角菜单发起或openShareDialog或openShare发起，分享完后一定执行此回调
		if (state == 1) {
			//分享成功
			// alert(data.type);//分享平台
			uni.showToast({
				title:'分享成功',
				icon:'none',
				duration:3000
			})
		} else {
			//分享失败
			// alert(data.error);//失败原因
			uni.showToast({
				title:'分享失败',
				icon:'none',
				duration:3000
			})
		}
		// QFH5.openShareDialog()
	}, 2, '')
}
//分享
export function shareApp() {
	QFH5.openShareDialog()
}
//代理分享  默认使用这个
export function proxyShareFun(title, imgUrl, desc, link,wxMiniProgram=null,callBack=()=>{},urlSx=''){
	let domain = store.state.siteinfo.main_hd_domian
	let needLink = ''
	if(link.indexOf('http')>-1){
		needLink = link.replace(/^http(s)?:\/\/(.*?)\//,'/')
	}else {
		needLink = link
	}
	let proxyUrl =  domain ? domain + '/site/redirect?path=' + encodeURIComponent(needLink): link
	
	if(process.env.NODE_ENV=="development"){
		proxyUrl = link
	}
	if(isQianfan()){
		try {
			//urlSx  私信参数
			console.log('sucess-----',urlSx)
			if (wxMiniProgram !== null) {
				QFH5.setShareInfo( title, imgUrl, desc, proxyUrl,
					function (state, data) {
						if (state == 1 && (data.type == 1 || data.type == 2)) {
							typeof callBack === 'function' && callBack()
						}
					}, 3, urlSx, JSON.stringify(wxMiniProgram),
				)
			} else {
				QFH5.setShareInfo(title, imgUrl, desc, proxyUrl, function (state, data) {
					if (state == 1 && (data.type == 1 || data.type == 2)) {
						typeof callBack === 'function' && callBack()
					}
				},1, urlSx)
			}
		} catch (e) {
			console.log(e)
		}
		return
	}
	if(isWeiXin()){
		let url = window.location.href
		let postData = {}
		postData.url = url
		postData.actid = uni.getStorageSync('actid') || ''
		wechatShare(postData).then(function (res) {
			let data = res.data
			wxModule.config(data)
		})
		wxModule.ready(function () {
			console.log('ready')
			wxModule.onMenuShareAppMessage({
				title: title,
				desc: desc,
				link: proxyUrl,
				imgUrl: imgUrl,
			})
			wxModule.onMenuShareTimeline({
				title: title,
				desc: desc,
				link: proxyUrl,
				imgUrl: imgUrl,
			})
		    wxModule.updateAppMessageShareData({
		        title: title,
		        desc: desc,
		        link: proxyUrl,
		        imgUrl: imgUrl,
		    })
		    wxModule.updateTimelineShareData({
		        title: title,
		        desc: desc,
		        link: proxyUrl,
		        imgUrl: imgUrl,
		    })
			callBack();
		})
		return
	}
}
// 分享
export function shareFun(title, imgUrl, desc, link, wxMiniProgram = null, callBack,urlSx='') {
	if (isQianfan()) {
		try {
			//urlSx  私信参数
			console.log('sucess-----',urlSx)
			if (wxMiniProgram !== null) {
				QFH5.setShareInfo( title, imgUrl, desc, link,
					function (state, data) {
						if (state == 1 && (data.type == 1 || data.type == 2)) {
							typeof callBack === 'function' && callBack()
						}
					}, 3, urlSx, JSON.stringify(wxMiniProgram),
				)
			} else {
				QFH5.setShareInfo(title, imgUrl, desc, link, function (state, data) {
					if (state == 1 && (data.type == 1 || data.type == 2)) {
						typeof callBack === 'function' && callBack()
					}
				},1, urlSx)
			}
		} catch (e) {
			console.log(e)
		}
		return
	}
	if (isWeiXin()) {

		//设置微信分享
		// const wx = Vue.wechat
		let url = window.location.href
		let postData = {}
		postData.url = url
		// postData.url =  link
		postData.actid = uni.getStorageSync('actid') || ''
		console.log('readyBefore',postData,link)
		wechatShare(postData).then(function (res) {
			console.log('ready',res)
			let data = res.data
			wxModule.config(data)
		})
		wxModule.ready(function () {
			console.log('ready')
			wxModule.onMenuShareAppMessage({
				title: title,
				desc: desc,
				link: link,
				imgUrl: imgUrl,
			})
			wxModule.onMenuShareTimeline({
				title: title,
				desc: desc,
				link: link,
				imgUrl: imgUrl,
			})
            wxModule.updateAppMessageShareData({
                title: title,
                desc: desc,
                link: link,
                imgUrl: imgUrl,
            })
            wxModule.updateTimelineShareData({
                title: title,
                desc: desc,
                link: link,
                imgUrl: imgUrl,
            })
			callBack();
		})
		return
	}
	if (isMagApp()) {
		mag.setData({
			shareData: {
				title: title,
				des: desc,
				picurl: imgUrl,
				linkurl: link,
			},
		})
	}
}
//设置微信分享
export function setWechatShare(title,imgUrl,desc,link){
				//四个参数均不能为空  否則會失敗
			let url = window.location.href
			console.log('url',window.location)
			let postData = {}
			postData.url = url
			postData.actid = uni.getStorageSync('actid') || ''
			console.log('readyBefore',postData,link)
			wechatShare(postData).then(function (res) {
				console.log('ready',res)
				let data = res.data
				wxModule.config(data)
			})
			wxModule.ready(function () {
				console.log('ready')
				wxModule.onMenuShareAppMessage({
					title: title,
					desc: desc,
					link: link,
					imgUrl: imgUrl,
				})
				wxModule.onMenuShareTimeline({
					title: title,
					desc: desc,
					link: link,
					imgUrl: imgUrl,
				})
			    wxModule.updateAppMessageShareData({
			        title: title,
			        desc: desc,
			        link: link,
			        imgUrl: imgUrl,
			    })
			    wxModule.updateTimelineShareData({
			        title: title,
			        desc: desc,
			        link: link,
			        imgUrl: imgUrl,
			    })
			})
}
//获取系统信息
export function getSystemInfo(){
	return new Promise((resolve,reject)=>{
		QFH5.getSystemInfo(function (state,data){
		    if(state==1){
					 uni.setStorage({
					 	key:'windowDec',
						data:JSON.stringify(data)
					 })
					 resolve(data)
		    }else{
		        //获取系统信息状态失败
		        // alert(data.error);//data.error: string
		    }
		})
	})
}
//设置内容标题
export function setTitle(title) {
	if (isQianfan()) {
		QFH5.setTitle(title)
		document.title = title
	} else {
		setDocumentTitle(title)
	}
}

//跳转方式	// qianfanyidong://webview?model=2&url=http%3A%2F%2F192.168.26.168%3A8080%2F%23%2F&type=mini&animate=true&isHome=true
//使用原生跳转方式model=-1 ;1 为沉浸状态栏 2为不嵌入状态栏
export function navigateTo(params={url:""},model=1){
	if(model==-1){
		uni.navigateTo(params)
	}else{
		// try{
		// 	let host=""
		// 	uni.getStorage({
		// 		key:'packagename',
		// 		success:(e)=>{
		// 			host = e.data
		// 		}
		// 	})
		// 	let url = window.location.origin+'/tbk-view'+params.url
		// 	let openUrl =""+ host+"://webview?model="+model+"&type=mini&animate=true&isHome=false"+"&url="+encodeURIComponent(url)
		// 	QFH5.jumpNewWebview(openUrl)
		// }catch(e){
			uni.navigateTo(params)
			// #ifdef APP-PLUS || H5
			// uni.navigateTo(params)
			// #endif
			// #ifdef MP-WEIXIN
			console.log('prize',params)
			// uni.navigateTo({
			// 	url:'./prize'
			// })
			// #endif

			// wx.navigateTo({
			// 	url:'/plugin/pages/guess/prize'
			// })
		// }
	}
	// uni.navigateTo(params)
}


//app操作地址--
export function newJumpUrl (type, param) {
	let scheme_url = getSchemeUrl(type)
	let request_host = store.state.siteinfo.request_host
	let app_pinyin = store.state.siteinfo.app_pinyin
	let jump_url = ''
	if (isIos()) {
		jump_url = request_host +'/'+scheme_url + param
		return jump_url
	}
	scheme_url = scheme_url + param
	scheme_url = encodeURIComponent(scheme_url)
	jump_url = 'http://a.app.qq.com/o/simple.jsp?pkgname=' + app_pinyin + '&android_schema=' + scheme_url
	return jump_url
}
// 根据不同类型获取客户端协议
export function getSchemeUrl (type) {
	let scheme_url = ''
	let package_name = store.state.siteinfo.package_name
	switch (type) {
		case schemeUrl.H5_WEB:
			scheme_url = package_name + '://webview/?url='
			break
		case schemeUrl.THREAD_INFO:
			scheme_url = package_name + '://thread/?tid='
			break
		case schemeUrl.SIDE_INFO:
			scheme_url = package_name + '://side/?sid='
			break
		case schemeUrl.TOPIC_INDEX:
			scheme_url = package_name + '://sidetag/?tid='
			break
		case schemeUrl.GROUP_INFO:
			scheme_url = package_name + '://group/?gid='
			break
		default:
			scheme_url = package_name + '://startapp'
	}
	return scheme_url
}
// ios解决document.title的问题
export function setDocumentTitle(title) {
	// #ifdef H5 || APP-PLUS
	document.title = title
	if (/ip(hone|od|ad)/i.test(navigator.userAgent)) {
		var i = document.createElement('iframe')
		i.src = '/favicon.ico'
		i.style.display = 'none'
		i.onload = function () {
			setTimeout(function () {
				i.remove()
			}, 9)
		}
		document.body.appendChild(i)
	}
	//#endif
}

// 是否是马甲app
export function isMagApp () {
	// #ifdef H5 || APP-PLUS
	let ua = window.navigator.userAgent.toLowerCase()
	if (ua.toLowerCase().search('magappx') !== -1) {
		return true
	} else {
		return false
	}
	//#endif
}

// 是否是移动端
export function isIphone () {
	// #ifdef H5 || APP-PLUS
	if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
		return true
	}
	//#endif
}

// 是否是ios
export function isIos () {
	// #ifdef H5 || APP-PLUS
	var u = navigator.userAgent
	var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
	return isiOS
	//#endif
}
//是否是Android
export function isAndroid () {
	// #ifdef H5 || APP-PLUS
	var u = navigator.userAgent
	var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
	if (isAndroid) {
		return true
	} else {
		return false
	}
	//#endif
}
//是否是微信
export function isWeiXin() {
	// #ifdef H5 || APP-PLUS
	let ua = window.navigator.userAgent.toLowerCase()
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		return true
	} else {
		return false
	}
	//#endif
}


//检查app是否登录
export function checkLogin() {
	return new Promise((resolve,recject)=>{
		let actid = uni.getStorageSync('actid') || null
		if(actid==null) actid = 0
		// #ifdef MP-WEIXIN
			console.log('检查微信',mp)
			let mp = requireMiniProgram()
			mp.getUserInfo().then(async res=>{
				console.log('检查微信',res)
				if(!res){
					resolve(false)
				}else{
					let user = await miniLogin({
						token: res.bearerToken,
						unionid: res.unionId,
						openid: res.openId,
						phone: res.phone
					})
					console.log(user)
					uni.setStorageSync(actid+'bearerToken',res.bearerToken)
					console.log('设置成功了',actid,uni.getStorageSync(actid+'bearerToken'))
					resolve(true)
				}
			})
		// #endif
		// #ifdef  H5
		if(isWeiXin()){
			let bearerToken = uni.getStorageSync(actid+'bearerToken') || null
			let bearerToken_expire = uni.getStorageSync(actid+'bearerToken_expire') || null
			if(bearerToken==null){
				resolve(false)
			}else if(bearerToken_expire!=null && (Date.parse(new Date())/1000) < bearerToken_expire){
				resolve(true)
			}else{
				resolve(false)
			}
		}
		else if(isQianfan()){
			QFH5.getUserInfo(function(state,data1){
			     if(state==1){
					 // console.log(state,data1)
			       //登陆状态，有数据
				   let data = {
					   uid:data1.uid,
					   username:data1.username,
					   avatar:data1.face,
					   deviceid:data1.deviceid,
					   phone:data1.phone
				   }
				   let loginInfo  = store.state.loginInfo
				   let newdata = Object.assign({},loginInfo,data)
			       /*var uid = data.uid;//用户UID int
			       var username = data.username;//用户名称 string
			       var avatar = data.face;//用户头像地址 string
			       var deviceid = data.deviceid;//用户设备唯一ID并MD5加密 string
			       var phone = data.phone;//用户绑定的手机号，没有绑定手机号给空字符串*/
				   store.dispatch('setLoginInfo',newdata)
			       resolve(true)

			     }else{
			       //未登录
			      resolve(false)
			     }
			   });
		}
		else{
			// uni.showToast({
			// 	title:'现在还不支持直接打开呢！请在微信内或者App内打开！',
			// 	icon:'none',
			// 	duration:3000
			// })
			resolve(false)
		}
		// #endif
		//都不是默认检查token
		// let token = uni.getStorageSync('bearerToken') || null
		// if(token==null){
		// 	resolve(false)
		// }else{
		// 	resolve(true)
		// }
	})
}

//拉起app登录
export function LoginApp(aid=0,redirect='') {
	if(aid==0){
		aid = uni.getStorageSync('actid') || 0
	}
	//检查是否有皮肤 否則登錄会丢失
	uni.setStorageSync(aid+'SkinType',store.state.skinType)
	// #ifdef MP-WEIXIN
		let mp = requireMiniProgram()
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const url = `/${currentPage.route}?id=${aid}`;
		let loginPath = mp.getMiniprogramPage('login') +'?redirect='+ encodeURIComponent(url)
		wx.redirectTo({url: loginPath})
	// #endif
	// #ifdef H5
		if(isWeiXin()){
			let url =window.location.protocol+'//'+ window.location.host+'/plugin-view/plugin/pages/guess/wechat'
			let rUrl = window.location.pathname+window.location.search
			let pathname = window.location.pathname
			let op = window.location.search
			if(pathname=='/plugin-view' || pathname=='/plugin-view/'){
				rUrl = '/'+op
			}else{
				rUrl =rUrl.replace(/\/plugin-view/,'')
			}
			uni.setStorageSync('rUrl',JSON.stringify({rUrl:redirect!=''?redirect:rUrl,id:aid}))
			getWechatAuth({return_url:encodeURIComponent(url),actid:aid,plugin:'weixin'}).then(res=>{
				window.location.href = res.data.auth_url
			})
		}
		if(isQianfan()){
			QFH5.jumpLogin(()=>{})
		}
	// #endif
	return false
}

//查验活动平台
export function checkPlatform(){
	let arr = uni.getStorageSync('platform') || null
	if(!arr){return false}
	arr = JSON.parse(arr)
	let text = ''
	arr.forEach((item,index)=>{
		switch(item){
			case 'wx': text=text+"微信" ;break;
			case 'app': text=text+"APP"; break;
			case 'mp': text=text+"小程序"; break;
		}
	})
	store.dispatch('setGuidePlatText',text)
	let platString = arr.join(',')
	let plat = false
	if(isWeiXin() && platString.indexOf('wx')>-1){plat = true}
	if(isQianfan() && platString.indexOf('app')>-1){plat = true}
	// #ifdef MP-WEIXIN
		// if( platString.indexOf('mp')>-1){plat = true}
		plat = true
	// #endif
	return plat
}
//返回图片
export function checkImage(type=1,image=null){
	switch(Number(type)){
		case 1:
			if(image.indexOf('http')>-1){
				return image
			}
			let host = store.state.qiniuUrl
			host= host.replace(/\/guess/,'')
			return host+image
		case 2:return store.state.qiniuUrl+'bag.png'
		case 3:return store.state.qiniuUrl+'pop_mt.png'
		default:return image
	}
}

//授权微信、、绑定手机、
export function checkProcess(successBack=()=>{},failBack=()=>{}){
		let guideData = store.state.guide
		let actid = uni.getStorageSync('actid') || null
		if(!checkPlatform()){
			store.dispatch('setGuideShow',4)
			failBack()
			return
		}
		if(isQianfan()){
			if(!guideData.isWechat){
				store.dispatch('setGuideShow',1)
				failBack()
				return
			}
			if(guideData.phone==""){
				store.dispatch('setGuideShow',2)
				failBack()
				return
			}
			successBack()
		}else{
			successBack()
		}
}
export function getDeviceId(){
	return new Promise((resolve,reject)=>{

		QFH5.getDeviceId(function(state,data){
		  if(state==1){
		    //获取设备号成功
		    // deviceid = data.deviceid;//用户设备唯一ID并MD5加密 string
			resolve(data.deviceid)
		  }
		})
	})
}
/*登录前置操作*/
export async function checkLoginBefore(){
	let {isWechat,phone} = store.state.guide
	if(checkPlat()){
		let loginStatus = await checkLogin()
		console.info('loginStatus=' + loginStatus)
		if(!loginStatus){
			login()
			return false
		}
		console.info('isQianfan=',isQianfan())
		if(isQianfan()){
			if(!isWechat){
				store.dispatch('setGuideShow',1)
				return false
			}
			if(phone==""){
				store.dispatch('setGuideShow',2)
				return false
			}
			return true
		}else{
			return true
		}
	}
}



export function login(){
	if(checkPlat()){
		LoginApp(store.state.actid)
	}
}
//检查平台
export function checkPlat(){
	let plat = checkPlatform()
	if(!plat){
		store.dispatch('setGuideShow',4)
	}
	return plat
}

//统计接口
export async function countNum(id){
	uni.showLoading({
		title: '加载中'
	});
	let res = await guessSportsText({actid: id})
	console.info(res)
	return res.data
}
//统计接口
export async function countNumAnswer(id){
	uni.showLoading({
		title: '加载中'
	});
	let res = await guessSportsText({actid: id},'answer','answer')
	console.info(res)
	return res.data
}
//统计接口
export async function countNumCollect(id){
	let res = await guessSportsText({actid: id},'collect','collect')
	return res.data
}



// 经纬度回调
// 获取经度纬度
export function getLocationCallBack(state, data) {
	if (state === 1) {
		//获取成功
		store.commit('updateLong', data.longitude)
		store.commit('updateLat', data.latitude)
	} else {
		//获取失败
		store.commit('updateLong', '0')
		store.commit('updateLat', '0')
	}
	getLocationCallBackFun()
}
// 版本比较
export function isneedUpadteVersion(version_local, version_remote) {
	let need_update = false
	let version_local_arr = version_local.split('.')
	let version_remote_arr = version_remote.split('.')

	for (let i = 0; i < version_remote_arr.length; i++) {
		if (version_local_arr[i]) {
			if (version_remote_arr[i] > version_local_arr[i]) {
				//从左往右对比  找到一个高的就是要升级
				need_update = true
				return need_update
			} else if (version_remote_arr[i] < version_local_arr[i]) {
				//如果对比下来小，就不需要升级
				return need_update
			}
		} else if (version_remote_arr[i]) {
			need_update = true
			return need_update
		}
	}
}
// 获取经纬度
export function getLocation(where,type) {
    let status = ''
    // const wx = Vue.wechat
	let _this = this
    console.info(where)
    if(where){
        if('confirm' == type){
			uni.showModal({
                    title: '提示',
                    confirmText:'确定',
                    content: '打开位置信息，查看附近',   
					success() {
						wx.getLocation({
							type: 'wgs84',
							success (res) {
								status = 'success'
								store.commit('updateLong',res.longitude)
								store.commit('updateLat',res.latitude)
								getLocationCallBackFun(status)
							},
							fail(res){
								status = 'fail'
								getLocationCallBackFun(status)
							}
						})
					},
					fail() {
						status = 'fail'
						store.commit('updateLong', '0')
						store.commit('updateLat', '0')
						getLocationCallBackFun(status)
					}
			});
        }else{
            if(0 == store.state.long && 0 == store.state.lat){
                wx.getLocation({
                    type: 'wgs84',
                    success (res) {
                        status = 'success'
                        store.commit('updateLong',res.longitude)
                        store.commit('updateLat',res.latitude)
                        getLocationCallBackFun(status)
                        /*const latitude = res.latitude
                        const longitude = res.longitude
                        const speed = res.speed
                        const accuracy = res.accuracy*/
                    },
                    fail(res){
                        status = 'fail'
                        getLocationCallBackFun(status)
                    }
                })
            }else{
                status = 'success'
                getLocationCallBackFun(status)
            }
        }
    }else{
        try {
            if (isneedUpadteVersion(getCookie('qianfan_appcode'), '3.0')) {
                QFH5.getLocation('getLocationCallBack')
            } else {
                QFH5.getLocation(function (state, data) {
                    if (state === 1) {
                        //获取成功
                        status = 'success'
                        store.commit('updateLong', data.longitude)
                        store.commit('updateLat', data.latitude)
                    } else {
                        //获取失败
                        uni.showToast({
								 title: '授权失败，请打开手机设置为应用定位授权！',
								 duration:2000,
								 icon:'none'
                        })
                        status = 'fail'
                        store.commit('updateLong', '0')
                        store.commit('updateLat', '0')
                    }
                    getLocationCallBackFun(status)
                })
            }
        } catch (e) {
            status = 'fail'
            store.commit('updateLong', '0')
            store.commit('updateLat', '0')
            getLocationCallBackFun(status)
        }
    }
}
//获取腾讯验证码
export function tecenctCpta(data,type,plugin){
	return new Promise((resolve,recject)=>{
		getTecentCheck(data,type,plugin).then(res=>{
			resolve(res)
		})
	})
}

